package com.wuxiaolong.tools.servive.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;

/**
 * Description:
 *
 * @author Leo
 * @date 2019/8/14
 */
@Slf4j
@Getter
@Setter
@Service
@ConfigurationProperties(prefix = "oss")
public class OssFileServiceImpl {

    private String endPoint;
    private String path;
    private String bucketName;
    private String downloadHost;
    private String accessId;
    private String accessKey;

    private OSSClient client;

    @PostConstruct
    private void init() {
        client = new OSSClient(endPoint, new DefaultCredentialProvider(accessId, accessKey));
    }


    public String upload(String fileName, InputStream input, long length) {
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(length);
        client.putObject(bucketName, path+ fileName, input, objectMeta);

        return downloadHost + path +  fileName;
    }


    public boolean exists(String key) {
        try {
            getObjectMetadata(key);
            return true;
        } catch (OSSException e) {
            if (OSSErrorCode.NO_SUCH_KEY.equals(e.getErrorCode()) || OSSErrorCode.NO_SUCH_BUCKET.equals(e.getErrorCode())) {
                return false;
            } else {
                throw e;
            }
        }
    }


    public void uploadIfNotExists(String key, InputStream input, long length) {
        if (!exists(key)) {
            upload(key, input, length);
        }
    }


    public void downloadFile(String key, String filename) {
        client.getObject(new GetObjectRequest(bucketName, key),
                new File(filename));
    }

    private ObjectMetadata getObjectMetadata(String key) {
        return client.getObjectMetadata(bucketName, key);
    }
}
